//
//  TJMeViewController.m
//  PigMarket
//
//  Created by 张敬 on 2019/8/3.
//  Copyright © 2019年 pigmarket.oc. All rights reserved.
//

#import "TJMeViewController.h"
#import "SystemSetingViewController.h"
#import "LoginViewController.h"
#import "MessageViewController.h"
#import "SelectTagsViewController.h"
#import "AddressViewController.h"
#import "CommonQuestionsViewController.h"
#import "PrefectPersonalInfoViewController.h"
#import "ModifyPhotoViewController.h"
#import "DiscountCouponViewController.h"
#import "MyAdoptedViewController.h"
#import "MyAssetViewController.h"
#import "HelpViewController.h"
#import "InviteFriendsViewController.h"
#import "MeatShopListViewController.h"
#import "MeatCartViewController.h"
#import "MessageManageViewController.h"
#import "CollectionManagerViewController.h"
#import "RealNameViewController.h"
#import "QuestionnaireViewController.h"
#import "OrderListViewController.h"

#import "OrderStatusView.h"
#import "PhotoAlbumView.h"
#import "MyServiceView.h"
#import "UIView+Add.h"
#import "MeatMeHeader.h"
#import "MeatMeSectionTableViewCell.h"
#import "MeatMeOrderTableViewCell.h"
#import "MeatMeServiceTableViewCell.h"
#import "MeatMeSurveyTableViewCell.h"


@interface TJMeViewController ()

@property (nonatomic, strong) MeatMeHeader *header;
@property (nonatomic, strong) NSArray *icons;
@property (nonatomic, strong) NSArray *titles;
@property (nonatomic, strong) NSArray *sectionTitles;
@property (nonatomic, strong) NSMutableArray *requestDataArr;
@property (nonatomic, strong) UserDetailInfo *userDetailInfo;
@property (nonatomic, assign) BOOL isLogin;
@property (nonatomic, strong) TaskModel *taskModel;

@end

@implementation TJMeViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    UserInfo *userInfo = [UserInfoDataProvider sharedInstance].userInfo;
    self.isLogin = userInfo.isLogin;
    
    if (self.isLogin) {//登录状态
        [self requestHeaderData];
        [self requestServiceData];
        [self requestTaskData];
        
    }else {
        self.header.type = MeatMeHeaderType_NoLogin;
    }
}


- (void)setupUI
{
    self.sectionTitles = @[@"我的订单", @"", @"我的服务", @"干点儿活赚点儿钱", @""];
    self.icons = @[@"meat_me_ask", @"meat_me_question", @"meat_me_card", @"meat_me_quan"];
    self.titles = @[@"问卷调查", @"完善资料", @"身份认证", @"分享有礼"];

    [self.view addSubview:self.header];
}


- (void)setupLayout
{
    self.tableView.mj_y = _header.bottom;
    self.tableView.height = KScreenHeight - _header.height - TJ_TabBarHeight;
}


//个人资料数据请求
- (void)requestHeaderData {
    
    NSNumber *memberId = [UserInfoDataProvider sharedInstance].userInfo.memberId;
    @weakify(self);
    [[[PigMarketApi sharedInstance] getUserDetailInfoWithMemberId:memberId] subscribeNext:^(UserDetailInfo * _Nullable userDetailInfo) {
        @strongify(self);
        self.header.item = userDetailInfo;
        self.userDetailInfo = userDetailInfo;
        
        //保存是否三方绑定标识
        UserInfo *userInfo = [UserInfoDataProvider sharedInstance].userInfo;
        userInfo.qqOpenid = userDetailInfo.qqOpenid;
        userInfo.wbOpenid = userDetailInfo.wbOpenid;
        userInfo.wxOpenid = userDetailInfo.wxOpenid;
        userInfo.withdrawWx = userDetailInfo.withdrawWx;
        userInfo.memberName = userDetailInfo.memberName;//实名认证
        [UserInfoDataProvider sharedInstance].userInfo = userInfo;
        
    } error:^(NSError * _Nullable error) {
        @strongify(self);
        [self handlingError:error];
    }];
}


- (void)requestServiceData{
    
    @weakify(self);
    [[[MeatOrderApi sharedInstance] getMineServiceIs] subscribeNext:^(ServiceModel * _Nullable model) {
        @strongify(self);
        
        switch ([model.Memberidentity integerValue]) {
            case 1:
            {
                self.header.type = MeatMeHeaderType_Service;
            }
                break;
            case 2:
            {
                self.header.type = MeatMeHeaderType_NoService;
            }
                break;

            case 3:
            {
                self.header.type = MeatMeHeaderType_Auditting;
            }
                
                break;
                
            default:
            {
                self.header.type = MeatMeHeaderType_Failure;
            }
                break;
        }
    }];
}


- (void)requestApplyServiceManager{
    
    @weakify(self);
    [[[MeatOrderApi sharedInstance] getOrderDetailByType:@1] subscribeNext:^(ServiceModel * _Nullable model) {
        @strongify(self);
        [self showMyAlertWithMessage:model.returnReason confirmBtnTitle:@"确认" callBack:^{
            
        }];
        
    } error:^(NSError * _Nullable error) {
        @strongify(self);
        [self showMyAlertWithMessage:@"由于网络问题，请重新再试！" confirmBtnTitle:@"确认" callBack:^{
            
        }];
    }];
}

//干点活赚点钱豚倦奖励与验证
- (void)requestTaskData{
    
    @weakify(self);
    [[[MeatOrderApi sharedInstance] getTaskCheck] subscribeNext:^(TaskModel * _Nullable taskModel) {
        @strongify(self);
        self.taskModel = taskModel;
        [self localReloadTableViewBySection:3];
        
    } error:^(NSError * _Nullable error) {
        
    }];
}


#pragma mark - tableview delegate/dataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 5;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) return 2;
    if (section == 1) return 1;
    if (section == 2) return 2;
    if (section == 3) return 5;
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0)
    {
        return indexPath.row == 0 ?44 :85;
    }
    
    if (indexPath.section == 1) return 80;
    
    if (indexPath.section == 2)
    {
        return indexPath.row == 0 ?44 :251;
    }
    
    if (indexPath.section == 3)
    {
        return indexPath.row == 0 ?44 :75;
    }
   
    return 150;
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 10;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *sectionView = [[UIView alloc] init];
    sectionView.backgroundColor = KClearColor;
    return sectionView;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section != 1 && indexPath.section !=4 &&indexPath.row == 0) {
        MeatMeSectionTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MeatMeSectionTableViewCell"];
        
        if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
            [cell setSeparatorInset:UIEdgeInsetsMake(0, 0, 0, 0)];
        }
        
        cell.titleLab.text = self.sectionTitles[indexPath.section];
        cell.detailLab.hidden = indexPath.section ==0 ?NO :YES;
        
        return cell;
    }
    
    if (indexPath.section == 0 && indexPath.row ==1) {
        
        MeatMeOrderTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MeatMeOrderTableViewCell"];
        
        @weakify(self);
        //预支付
        cell.dealPayBlock = ^{
            @strongify(self);
            OrderListViewController *vc = [[OrderListViewController alloc] init];
            vc.currentIndex = 1;
            [self.navigationController pushViewController:vc animated:YES];
        };
        
        //待收款
        cell.dealAcceptBlock = ^{
            @strongify(self);

            OrderListViewController *vc = [[OrderListViewController alloc] init];
            vc.currentIndex = 2;
            [self.navigationController pushViewController:vc animated:YES];

        };
        
        //待评价
        cell.dealEvaluationBlock = ^{
            @strongify(self);

            OrderListViewController *vc = [[OrderListViewController alloc] init];
            vc.currentIndex = 3;
            [self.navigationController pushViewController:vc animated:YES];

        };
        
        //售后
        cell.dealServiceBlock = ^{
            @strongify(self);

            [self showHudWithMsg:@"售后"];
        };
        
        return cell;
    }
    
    if (indexPath.section == 2 && indexPath.row ==1) {
        
        MeatMeServiceTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MeatMeServiceTableViewCell"];
        
        @weakify(self);
        //我的收藏
        cell.dealCollectionBlock = ^{
            @strongify(self);
            CollectionManagerViewController *vc = [[CollectionManagerViewController alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
        };
        
        //豚券
        cell.dealVouchersBlock = ^{
            @strongify(self);
            DiscountCouponViewController *vc = [[DiscountCouponViewController alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
        };
        
        //我的资产
        cell.dealAssetsBlock = ^{
            @strongify(self);
            MyAssetViewController *vc = [[MyAssetViewController alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
        };
        
        //我的领养
        cell.dealAdoptBlock = ^{
            @strongify(self);
            MyAdoptedViewController *vc = [[MyAdoptedViewController alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
        };
        
        //购物车
        cell.dealCartBlock = ^{
            @strongify(self);
            MeatCartViewController *vc = [[MeatCartViewController alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
        };

        //收货地址
        cell.dealLocationBlock = ^{
            @strongify(self);
            AddressViewController *vc = [[AddressViewController alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
        };
        
        //常见问题
        cell.dealQuestionBlock = ^{
            @strongify(self);
            CommonQuestionsViewController *vc = [[CommonQuestionsViewController alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
        };
        
        //帮助
        cell.dealHelpBlock = ^{
            @strongify(self);
            HelpViewController *vc = [[HelpViewController alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
        };
        
        //我的肉铺
        cell.dealMeatShopBlock = ^{
            @strongify(self);
            MeatShopListViewController *vc = [[MeatShopListViewController alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
        };
        
        return cell;
    }
    
    if (indexPath.section == 3) {
        
        MeatMeSurveyTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MeatMeSurveyTableViewCell"];
        if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
            [cell setSeparatorInset:UIEdgeInsetsMake(0, 15, 0, 15)];
        }
        
        cell.icon.image = [UIImage imageNamed:self.icons[indexPath.row -1]];
        cell.nameLab.text = self.titles[indexPath.row -1];
        
        if (indexPath.row < self.taskModel.list.count + 1) {
            TaskDataModel *item = self.taskModel.list[indexPath.row -1];
            cell.item = item;
        }
        
        return cell;
    }
    
    
    BaseIndentationTableCell *cell = [tableView dequeueReusableCellWithIdentifier:@"BaseIndentationTableCell"];
    if (indexPath.section == 1 || indexPath.section == 4) {
        UIImage *image = [UIImage imageNamed:@"user_invitefriend"];
        cell.contentView.layer.contents = (__bridge id)image.CGImage;
    }
    return cell;
    
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (indexPath.section == 0 && indexPath.row == 0) {
        OrderListViewController *vc = [[OrderListViewController alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    }
    
    
    
    if (indexPath.section == 3) {
        
        if (indexPath.row < self.taskModel.list.count + 1) {
            TaskDataModel *item = self.taskModel.list[indexPath.row -1];
            BOOL isFinish = [item.verification integerValue] == 1 ? YES : NO;
            
            switch (indexPath.row) {
                case 1: //问卷调查
                {
                    if (isFinish) {
                        QuestionnaireViewController *vc = [[QuestionnaireViewController alloc]init];
                        [self.navigationController pushViewController:vc animated:YES];
                    }
                }
                    break;
                    
                case 2: //完善资料
                {
                    if (isFinish) {
                        PrefectPersonalInfoViewController *modifyUserInfoVC = [[PrefectPersonalInfoViewController alloc] init];
                        modifyUserInfoVC.title = ModifyPersonalInfoTitle;
                        modifyUserInfoVC.userInfoModel = self.userDetailInfo;
                        [self.navigationController pushViewController:modifyUserInfoVC animated:YES];
                    }
                }
                    break;
                    
                case 3: //身份认证
                {
                    if (isFinish) {
                        RealNameViewController *realNameVC = [[RealNameViewController alloc] init];
                        [self.navigationController pushViewController:realNameVC animated:YES];
                    }
                }
                    break;
                    
                case 4: //分享有礼
                {
                    if (isFinish) {
                        InviteFriendsViewController *friendVC = [[InviteFriendsViewController alloc] init];
                        [self.navigationController pushViewController:friendVC animated:YES];
                    }
                }
                    break;
                    
                default:
                    break;
            }
        }
    }
}

#pragma mark - other methods

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    [self.view endEditing:YES];
    CGFloat sectionHeaderHeight = 34;
    if(scrollView.contentOffset.y<=sectionHeaderHeight&&scrollView.contentOffset.y>=0) {
        scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
    } else if (scrollView.contentOffset.y>=sectionHeaderHeight) {
        scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0);
    }
}


#pragma mark - getter and setter

- (void)registerTableViewCell
{
    self.tableView.separatorColor = mIconLineColor;
    self.tableView.mj_footer.hidden = YES;
    self.tableView.mj_header.hidden = YES;

    
    [self.tableView registerClass:[BaseIndentationTableCell class] forCellReuseIdentifier:@"BaseIndentationTableCell"];
    [self.tableView registerClass:[MeatMeSectionTableViewCell class] forCellReuseIdentifier:@"MeatMeSectionTableViewCell"];
    [self.tableView registerClass:[MeatMeOrderTableViewCell class] forCellReuseIdentifier:@"MeatMeOrderTableViewCell"];
    [self.tableView registerClass:[MeatMeServiceTableViewCell class] forCellReuseIdentifier:@"MeatMeServiceTableViewCell"];
    [self.tableView registerClass:[MeatMeSurveyTableViewCell class] forCellReuseIdentifier:@"MeatMeSurveyTableViewCell"];
    
    UIView *footer = [UIView new];
    footer.backgroundColor = mBackgroudColor;
    footer.frame = CGRectMake(0, 0, KScreenWidth, 10);
    self.tableView.tableFooterView = footer;
    
}

- (MeatMeHeader *)header
{
    if (!_header) {
        _header = [[MeatMeHeader alloc] init];
        _header.type = MeatMeHeaderType_NoLogin;
        
        @weakify(self);
        //个人信息Block
        _header.dealUserInformationBlock = ^{
            @strongify(self);
            PrefectPersonalInfoViewController *modifyUserInfoVC = [[PrefectPersonalInfoViewController alloc] init];
            modifyUserInfoVC.title = ModifyPersonalInfoTitle;
            modifyUserInfoVC.userInfoModel = self.userDetailInfo;
            [self.navigationController pushViewController:modifyUserInfoVC animated:YES];
            
        };
        
        //消息Block
        _header.dealMessageBlock = ^{
            @strongify(self);
            MessageManageViewController *vc = [[MessageManageViewController alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
        };
        
        //设置Block
        _header.dealSetUpBlock = ^{
            @strongify(self);
            SystemSetingViewController *vc = [[SystemSetingViewController alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
        };
        
        
        //登陆|注册
        _header.dealRegistLoginBlock = ^{
            @strongify(self);
            LoginViewController *vc = [[LoginViewController alloc] init];
            [self.navigationController pushViewController:vc animated:YES];

        };
        
        //申请服务商
        _header.dealServiceBlock = ^{
            @strongify(self);
            if (self.isLogin) {//登录状态
                [self requestApplyServiceManager];
            }else {
                [self showHudWithMsg:@"您还没有登陆"];
            }
        };
    }
    
    return _header;
}

- (TaskModel *)taskModel{
    
    if (!_taskModel) {
        _taskModel = [[TaskModel alloc] init];
    }
    return _taskModel;
}

#pragma mark - notifications

- (void)loginStatusChanged:(NSNotification *)notification {
    if ([UserInfoDataProvider sharedInstance].userInfo.isLogin) { // 登录成功
        self.header.type = MeatMeHeaderType_NoService;
    }
}

- (void)addNotifications
{
    [kNotificationCenter addObserver:self selector:@selector(loginStatusChanged:) name:NotificationLoginStatusChanged object:nil];
}

- (void)removeNotifications
{
    [kNotificationCenter removeObserver:self name:NotificationLoginStatusChanged object:nil];
}

@end
